<!--
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2022-03-09 15:49:24
 * @LastEditors: Bobby
 * @Description:
 * @FilePath: \wms-v2\src\ve\elements\form\uiSelect\uiSelect.vue
 * CIMC-V2
-->
<template>
  <!-- <span>{{ optionList }}</span> -->
  <el-select
    :ref="moduleId"
    v-model="formData"
    :allow-create="info.extension.allowCreate && info.extension.allowCreate.value"
    class="w-full"
    clearable
    :default-first-option="true"
    :disabled="disabled"
    filterable
    :multiple="info.extension.multiple.value"
    :placeholder="translateTitle('Ve.elements.请选择')"
    size="mini"
    @keyup.enter="nextModuleFocus"
  >
    <el-option
      v-for="item in optionList"
      :key="`${item[info.extension.valueField.value]}_${postfixKey}`"
      :label="item[info.extension.labelField.value] || 'label'"
      :value="item[info.extension.valueField.value] || 'value'"
    >
      <span>{{ item[info.extension.labelField.value] }}</span>
    </el-option>
  </el-select>
</template>
<script>
  import { translateTitle } from '@/utils/i18n'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import { componentId } from '@/utils/unique'
  import isEmpty from 'lodash/isEmpty'
  import trim from 'lodash/trim'
  import isArray from 'lodash/isArray'
  import { customAlphabet } from 'nanoid'
  import { defineComponent } from 'vue'
  import { processingConstant, replaseRegVariable } from '@ve/utils/utils'
  import { tableFormItemMixin } from '@ve/mixin'
  export default defineComponent({
    name: 'UiTableSelect',
    components: {},
    mixins: [tableFormItemMixin],
    props: {
      rowData: {
        require: true,
        type: Object,
        default: () => {
          return {}
        },
      },
    },
    data() {
      return {
        optionList: [],
        lastNewval: {},
        postfixKey: 'aa',
      }
    },
    computed: {
      formData: {
        get() {
          let returnVal = this.formDataItem[this.formDataKey]
          if (this.info.extension.multiple.value) {
            // 如果是多选的话 需要将值做一个拆分
            returnVal = returnVal && returnVal.split(',')
          }
          return returnVal
        },
        set(value) {
          let label = ''
          if (this.info.extension.multiple.value) {
            // 组织label值
            const labelList = []
            value.forEach((i) => {
              this.optionList.forEach((oi) => {
                if (oi[this.info.extension.valueField.value || 'value'] === i) {
                  labelList.push(oi[this.info.extension.labelField.value || 'label'])
                }
              })
            })
            // 如果是多选的话 则需要将值拼接
            value = isArray(value) ? value.join(',') : value
            label = labelList.join(',')
          } else if (value === null) {
            // 如果是null值则转化为空字符串
            value = ''
          } else {
            // 单选模式下获取label
            this.optionList.forEach((oi) => {
              if (oi[this.info.extension.valueField.value || 'value'] === value) {
                label = oi[this.info.extension.labelField.value || 'label']
              }
            })
          }
          this.formDataItem[this.formDataKey] = value
          if (this.formDataKey !== this.formDataLabel) this.formDataItem[this.formDataLabel] = label
        },
      },
    },
    watch: {},
    created() {
      // 生成组件ID
      this.moduleId = `uiTableSelect_${componentId(6)}`
      this.optionList = this.info.extension.optionConfig.value
    },
    mounted() {
      // 添加组件实例至状态管理器存储
      if (!this.disabled)
        this.$store.dispatch('tableFormItem/setTableFormItemList', {
          id: this.moduleId,
          ref: this.$refs[this.moduleId],
        })
      // 判断是否有配置获取选项
      if (this.hasPreview && this.info.extension.api.value) {
        this.requestOptionList()
      }
    },
    methods: {
      translateTitle,
      requestOptionList() {
        let requestDataObj = {}
        isArray(this.info.extension.requestData.value) &&
          this.info.extension.requestData.value.forEach((item) => {
            let itemVal = item.value
            // 判断是否有变量配置
            if (/#{.*?}/g.test(item.value)) {
              // 变量解析
              itemVal = replaseRegVariable(itemVal, this.rowData)
            }
            // 常量解析
            requestDataObj[item.key] = processingConstant(this, itemVal)
          })
        let options = {
          api: this.info.extension.api.value,
          method: this.info.extension.method.value,
          getDataKey: this.info.extension.getDataKey.value,
          data: requestDataObj,
        }
        if (!trim(options.api)) return
        this.request(options)
      },
      request(options = {}) {
        this.loading = true
        let getDataKey = options.getDataKey
        //发起请求
        return request({
          url: GFCD('dams', 'domain') + options.api,
          method: 'post',
          data: {
            data: JSON.stringify(options.data),
            method: options.method,
          },
        }).then((res) => {
          this.loading = false
          //解密
          // console.log(decryptd(res))
          // this.getInfo.data.requestData = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
          this.optionList = isEmpty(getDataKey) ? res.data.data || [] : res.data[getDataKey].data || []
          this.postfixKey = this.componentId()
        })
      },
      componentId() {
        const nanoid = customAlphabet('abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMN', 6)
        return nanoid()
      },
    },
  })
</script>
<style lang="scss" scoped></style>
